package com.itxxl.controller;

import com.itxxl.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping(path = "/user")
@SessionAttributes(value = {"user"})
public class UserController {

    @RequestMapping(path = "/testString")
    public String testString(Model model){
        System.out.println("testString运行了");

        User user = new User();
        user.setUsername("妹妹");
        user.setPassword("123");
        user.setAge(15);
        model.addAttribute("user",user);
        return "success";
    }


    @RequestMapping(path = "/testVoid")
    public void testString(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("testVoid运行了");
        //编写请求转发的程序
        //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);

        //重定向
        //response.sendRedirect(request.getContextPath()+"index.jsp");

        //设置中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //直接响应
        response.getWriter().print("你好");
        return;
    }

    @RequestMapping(path = "/testModelAndView")
    public ModelAndView testModelAndView(){
        //创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        System.out.println("testModelAndView执行了");
        //从数据库中查询出User对象
        User user = new User();
        user.setUsername("妹妹");
        user.setPassword("123");
        user.setAge(15);

        //把user对象储存到mv对象中，也会把usr对象存入到request对象
        mv.addObject("user",user);

        //跳转到哪个页面
        mv.setViewName("success");
        return mv;
    }

    /*
    * 使用关键字的方式进行转发或者重定向
    * */
    @RequestMapping(path = "/testForwardOrRedirect")
    public String testForwardOrRedirect(){
        System.out.println("testForwardOrRedirect方法执行了");

        //请求的转发
        //return "forward:/WEB-INF/pages/success.jsp";

        //重定向
        return "redirect:/index.jsp";
    }

    @RequestMapping(path = "/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax执行了");
        //客户端发送ajax的请求，传的是json字符串，后端把json字符串封装到user对象中
        System.out.println(user);
        //做响应，模拟查询数据库
        user.setUsername("haha");
        user.setAge(16);
        //做响应
        return user;
    }
}
